package core;

import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.model.annotation.ExtractBy;



/**
 * The extension to Pipeline for page model extractor.
 * 
 * @author code4crafter@gmail.com <br>
 * @since 0.2.0
 */
public class ModelPipeline implements Pipeline {

	@SuppressWarnings("rawtypes")
	private Map<Class, PageModelPipeline> pageModelPipelines = new ConcurrentHashMap<Class, PageModelPipeline>();

	public ModelPipeline() {
	}

	public ModelPipeline put(Class<?> clazz,
			PageModelPipeline<?> pageModelPipeline) {
		pageModelPipelines.put(clazz, pageModelPipeline);
		return this;
	}

	@SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
	public void process(ResultItems resultItems, Task task) {
		for (Map.Entry<Class, PageModelPipeline> classPageModelPipelineEntry : pageModelPipelines
				.entrySet()) {
			boolean isSkip = resultItems
					.getFieldSkip(classPageModelPipelineEntry.getKey()
							.getCanonicalName());
			if (isSkip) {
				continue;
			}
			Object o = resultItems.get(classPageModelPipelineEntry.getKey()
					.getCanonicalName());
			if (o != null) {
				Annotation annotation = classPageModelPipelineEntry.getKey()
						.getAnnotation(ExtractBy.class);
				if (annotation == null || !((ExtractBy) annotation).multi()) {
					classPageModelPipelineEntry.getValue().process(o, task);
				} else {
					List<Object> list = (List<Object>) o;
					for (Object o1 : list) {
						classPageModelPipelineEntry.getValue()
								.process(o1, task);
					}
				}
			}
		}
	}
}
